import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import User from '../models/user.js';

const router = express.Router();

// 获取购物车
router.get('/', authenticateToken, async (req, res) => {
  try {
    const cart = await User.getCart(req.user.id);
    
    // 处理图片路径
    const processedCart = cart.map(item => ({
      ...item,
      image: item.image && !item.image.startsWith('http')
        ? `${req.protocol}://${req.get('host')}/uploads/${item.image}`
        : item.image
    }));
    
    res.json(processedCart);
  } catch (error) {
    console.error('Error in GET /cart:', error);
    res.status(500).json({ 
      success: false,
      message: '获取购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 获取购物车商品数量
router.get('/count', authenticateToken, async (req, res) => {
  try {
    // 检查用户是否已有购物车
    const cart = await User.getCart(req.user.id);
    
    if (cart.length === 0) {
      return res.json({ count: 0 });
    }
    
    // 获取购物车商品总数量
    const result = await User.getCartItemCount(req.user.id);
    
    res.json({ count: result[0].count || 0 });
  } catch (error) {
    console.error('Error fetching cart count:', error);
    res.status(500).json({ message: '获取购物车数量失败' });
  }
});

// 添加商品到购物车
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { product_id, quantity, attributes } = req.body;
    
    if (!product_id) {
      return res.status(400).json({ 
        success: false,
        message: '商品ID不能为空' 
      });
    }
    
    const cartItemId = await User.addToCart(
      req.user.id, 
      product_id, 
      quantity || 1,
      attributes
    );
    
    res.status(201).json({ 
      success: true,
      message: '商品已添加到购物车',
      cart_item_id: cartItemId
    });
  } catch (error) {
    console.error('Error in POST /cart:', error);
    res.status(500).json({ 
      success: false,
      message: '添加到购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 更新购物车商品数量
router.put('/item/:id', authenticateToken, async (req, res) => {
  try {
    const { quantity } = req.body;
    const cartItemId = req.params.id;
    
    if (!quantity || quantity < 1) {
      return res.status(400).json({ 
        success: false,
        message: '数量必须大于0' 
      });
    }
    
    await User.updateCartItemQuantity(req.user.id, cartItemId, quantity);
    
    res.json({ 
      success: true,
      message: '购物车已更新'
    });
  } catch (error) {
    console.error('Error in PUT /cart/item/:id:', error);
    res.status(500).json({ 
      success: false,
      message: '更新购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 从购物车中删除商品
router.delete('/item/:id', authenticateToken, async (req, res) => {
  try {
    const cartItemId = req.params.id;
    
    await User.removeFromCart(req.user.id, cartItemId);
    
    res.json({ 
      success: true,
      message: '商品已从购物车中删除'
    });
  } catch (error) {
    console.error('Error in DELETE /cart/item/:id:', error);
    res.status(500).json({ 
      success: false,
      message: '从购物车中删除商品失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 清空购物车
router.delete('/', authenticateToken, async (req, res) => {
  try {
    await User.clearCart(req.user.id);
    
    res.json({ 
      success: true,
      message: '购物车已清空'
    });
  } catch (error) {
    console.error('Error in DELETE /cart:', error);
    res.status(500).json({ 
      success: false,
      message: '清空购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 应用优惠码
router.post('/promo', authenticateToken, async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({ 
        success: false,
        message: '优惠码不能为空' 
      });
    }
    
    const result = await User.applyPromoCode(req.user.id, code);
    
    res.json({ 
      success: true,
      message: '优惠码已应用',
      discount: result
    });
  } catch (error) {
    console.error('Error in POST /cart/promo:', error);
    res.status(400).json({ 
      success: false,
      message: error.message || '应用优惠码失败'
    });
  }
});

// 计算配送费
router.post('/shipping', authenticateToken, async (req, res) => {
  try {
    const { country, province, city, postcode } = req.body;
    
    if (!country) {
      return res.status(400).json({ 
        success: false,
        message: '国家/地区不能为空' 
      });
    }
    
    const result = await User.calculateShipping(req.user.id, {
      country,
      province,
      city,
      postcode
    });
    
    res.json({ 
      success: true,
      ...result
    });
  } catch (error) {
    console.error('Error in POST /cart/shipping:', error);
    res.status(500).json({ 
      success: false,
      message: error.message || '计算配送费失败'
    });
  }
});

export default router; 